package org.xhy.chameleon.config;

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.xhy.beanchameleon.compiler.MemoryCompiler;
import org.xhy.beanchameleon.core.ChameleonHandler;
import org.xhy.beanchameleon.service.MemoryChameleonManager;
import org.xhy.beanchameleon.loader.DynamicClassLoader;

import org.xhy.beanchameleon.pipeline.ChainController;

import org.xhy.beanchameleon.pipeline.ChainProcess;
import org.xhy.beanchameleon.validator.ChameleonValidator;
import org.xhy.beanchameleon.pipeline.ChainTemplate;
import org.xhy.chameleon.boot.ChameleonSpringFactory;

import java.util.*;

/**
 * @description: 自动装配
 * @gitee: https://gitee.com/XhyQAQ
 * @copyright: B站: https://space.bilibili.com/152686439
 * @Author: Xhy
 * @CreateTime: 2024-03-25 20:40
 */
@Configuration
public class EnableAutoConfigChameleon {

    @Bean
    public MemoryChameleonManager memoryChameleonManager(){
        return new MemoryChameleonManager();
    }

    @Bean
    @ConditionalOnMissingBean(ChameleonHandler.class)
    public ChameleonHandler chameleonActionHandler(ChameleonSpringFactory managerService){
        return new ChameleonHandler(managerService);
    }

    @Bean
    public ChameleonValidator ChameleonValidator(){
        return new ChameleonValidator();
    }

    @Bean
    public MemoryCompiler memoryCompiler(){
        return new MemoryCompiler();
    }

    @Bean
    public DynamicClassLoader dynamicClassLoader(){
        return new DynamicClassLoader();
    }

    @Bean
    public ChameleonSpringFactory chameleonSpringFactory(DefaultListableBeanFactory defaultListableBeanFactory){
        return new ChameleonSpringFactory(defaultListableBeanFactory);
    }

    @Bean
    @ConditionalOnMissingBean(ChainTemplate.class)
    public ChainTemplate chainTemplate(ChameleonValidator ChameleonValidator,
                                       MemoryCompiler memoryCompiler,
                                       DynamicClassLoader dynamicClassLoader,
                                       ChameleonSpringFactory chameleonSpringFactory){
        final List<ChainProcess> list = Arrays.asList(ChameleonValidator,memoryCompiler,dynamicClassLoader,chameleonSpringFactory);
        final Map<String, Collection<ChainProcess>> chameleons = new HashMap<>();
        chameleons.put(ChainTemplate.DEFAULT,list);
        return new ChainTemplate(chameleons);
    }

    @Bean
    @ConditionalOnMissingBean(ChainController.class)
    public ChainController chainController(ChainTemplate chainTemplate){
        ChainController chainController = new ChainController();
        chainTemplate.getTemplates().forEach((k,v)->{
            chainController.addChain(k,v);
        });
        return chainController;
    }

}
